<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号id" prop="accountId">
        <el-input
          v-model="queryParams.accountId"
          placeholder="请输入账号id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分组标题" prop="groupTitle">
        <el-input
          v-model="queryParams.groupTitle"
          placeholder="请输入分组标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['media:accountGroup:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['media:accountGroup:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['media:accountGroup:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['media:accountGroup:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountGroupList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分组标题" align="center" prop="groupTitle" />
      <el-table-column label="该分组账号数" align="center" prop="accountCount" >
        <template slot-scope="scope">
          <div>
            {{scope.row.accountList.length}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分组账号昵称" align="center" prop="accountId" >
        <template slot-scope="scope">
          <div>
            <template v-for="account in scope.row.accountList">
              <div>{{ account.nickname }}</div>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分组账号头像" align="center" prop="accountId" >
        <template slot-scope="scope">
          <div>
            <template v-for="account in scope.row.accountList">
              <img style="height: 30px;width: 30px;border-radius: 15px" :src="account.headImgUrl" />
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['media:accountGroup:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['media:accountGroup:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账号分组对话框 -->
    <el-dialog :title="title" :visible.sync="open" :before-close="handleClose"  width="800px" append-to-body>
      <div style="margin: 20px;color: #767676;font-size: 17px">提示：选中已被分组的账号，将重新分组。</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分组标题" prop="groupTitle">
          <el-input v-model="form.groupTitle" placeholder="请输入分组标题" />
        </el-form-item>

        <el-form-item label="分组账号" prop="selectAccount">
          <el-form :model="accountQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="账号昵称" prop="nickname">
              <el-input
                v-model="accountQueryParams.nickname"
                placeholder="请输入账号昵称"
                clearable
                @keyup.enter.native="getAccountData"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getAccountData">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table ref="multipleTable"  v-loading="loading" style="width: 100%" height="400" :data="accountList"
                    border   @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="账号头像" align="center" prop="headImgUrl" >
              <template slot-scope="scope">
                <img :src="scope.row.headImgUrl" style="width: 50px;height: 50px;border-radius: 50px">
              </template>
            </el-table-column>
            <el-table-column label="账号昵称" align="center" prop="nickname" >
              <template slot-scope="scope">
                <span style="font-size: 13px;color: #646464;">{{scope.row.nickname}}</span>
              </template>
            </el-table-column>
            <el-table-column label="平台" align="center" prop="platform" >
              <template slot-scope="scope">
                <img :src="require('@/assets/media/' + scope.row.platformCode + '.png' )" style="width: 30px;height: 30px;border-radius: 50px">
              </template>
            </el-table-column>
            <!--      <el-table-column label="平台图标" align="center" prop="logo" /> -->
            <el-table-column label="账号登录状态" align="center" prop="loginStatus" >
              <template slot-scope="scope">
                <el-tag :type="scope.row.loginStatus === 1 ? '' : 'danger'"
                        style="cursor:pointer" >
                  {{scope.row.loginStatus === 1 ? '已登录' : '已掉线'}}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="最后扫码时间" sortable align="center" prop="lastScanTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.lastScanTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="accountTotle>0"
            :total="accountTotle"
            :page.sync="accountQueryParams.pageNum"
            :limit.sync="accountQueryParams.pageSize"
            @pagination="getAccountData"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitFormGroupData">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAccountGroup, getAccountGroup, delAccountGroup, addAccountGroup, updateAccountGroup } from "@/api/media/accountGroup";
import { listMediaAccount } from "@/api/media/mediaAccount";
import {Message} from "element-ui";
export default {
  name: "AccountGroup",
  data() {
    return {
      accountList:{},
      accountTotle:0,
      isUpdate:false,
      accountQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname:undefined,
        accountId: undefined,
        groupTitle: undefined
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账号分组表格数据
      accountGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      checkedAccountList:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        userId: undefined,
        accountId: undefined,
        groupTitle: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门id不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        accountId: [
          { required: true, message: "账号id不能为空", trigger: "blur" }
        ],
        groupTitle: [
          { required: true, message: "分组标题不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAccountData();
  },
  methods: {
    /** 查询账号分组列表 */
    getList() {
      this.loading = true;
      listAccountGroup(this.queryParams).then(response => {
        this.accountGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },


    /**
     * 获取账号数据
     */
    getAccountData(){
      this.loading = true;
      listMediaAccount(this.accountQueryParams).then((res)=>{
        this.accountList = res.rows;
        this.accountTotle = res.total;
        this.loading = false;
      })
      setTimeout(()=>{
        this.checkedAccount();
      },1000)

    },


    /**
     * 提交账号分组
     */
    submitFormGroupData(){
      let data = Object.assign({}, this.form, {ids:this.ids});
      if(this.isUpdate){
        updateAccountGroup(data).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.handleClose();
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      }else{
        addAccountGroup(data).then((res)=>{
          Message.success("操作成功！")
          this.handleClose()
          this.getList();
        })
      }
    },

    /**
     * 关闭弹框
     */
    handleClose(){
      this.open = false;
      this.isUpdate = false;
      this.$refs.multipleTable.clearSelection();
      this.ids = []
      this.reset();
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.handleClose()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        userId: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        accountId: undefined,
        groupTitle: undefined,
        groupId:undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加账号分组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.isUpdate = true
      const id = row.id || this.ids
      getAccountGroup(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改账号分组";
        //选中账号行数据
        this.checkedAccountList = response.data.accountList;
        this.checkedAccount();
      });
    },


    /**
     * 将已分组的账号选中
     */
    checkedAccount(){
      let that = this;
      if(this.checkedAccountList && this.checkedAccountList.length > 0){
        this.accountList.forEach((item)=>{
          for(let i = 0 ; i < this.checkedAccountList.length; i++ ){
            if(item.id === this.checkedAccountList[i].id){
              setTimeout(()=>{
                that.$refs.multipleTable.toggleRowSelection(item,true);
              },1000)
            }
          }
        })
      }
    },



    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateAccountGroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAccountGroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除账号分组编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delAccountGroup(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('media/accountGroup/export', {
        ...this.queryParams
      }, `accountGroup_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
